<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org"
      xmlns:layout="http://www.ultraq.net.nz/thymeleaf/layout"
      layout:decorate="~{layout/base}">
<head>
    <title>学生列表</title>
    <style>
        .search-card {
            background-color: #f8f9fa;
            border: none;
            box-shadow: 0 0.125rem 0.25rem rgba(0,0,0,.075);
        }
        
        .table th {
            background-color: #f8f9fa;
            font-weight: 600;
        }
        
        .action-buttons .btn {
            padding: 0.25rem 0.5rem;
            font-size: 0.875rem;
        }
        
        .search-form .form-control {
            border-radius: 20px;
        }
        
        .search-form .btn {
            border-radius: 20px;
            padding-left: 1.5rem;
            padding-right: 1.5rem;
        }
        
        .table-responsive {
            border-radius: 0.25rem;
            box-shadow: 0 0.125rem 0.25rem rgba(0,0,0,.075);
        }
        
        .pagination {
            margin-bottom: 0;
        }
        
        .badge {
            font-weight: 500;
        }
        
        /* 加载遮罩层样式 */
        .loading-overlay {
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background-color: rgba(0, 0, 0, 0.5);
            display: flex;
            justify-content: center;
            align-items: center;
            z-index: 9999;
        }

        .loading-overlay .spinner-border {
            width: 3rem;
            height: 3rem;
            color: #fff;
        }

        /* Toast样式 */
        .toast-container {
            position: fixed;
            top: 20px;
            right: 20px;
            z-index: 10000;
        }

        .toast {
            min-width: 250px;
            opacity: 0;
            transition: opacity 0.3s ease-in-out;
        }

        .toast.show {
            opacity: 1;
        }

        /* 表格操作按钮样式优化 */
        .action-buttons .btn {
            margin: 0 2px;
            transition: all 0.2s ease;
        }

        .action-buttons .btn:hover {
            transform: translateY(-1px);
            box-shadow: 0 2px 4px rgba(0,0,0,0.1);
        }
    </style>
</head>
<body>
    <!-- Delete Confirmation Modal -->
    <div class="modal fade" id="deleteConfirmModal" tabindex="-1">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title">
                        <i class="bi bi-exclamation-triangle-fill text-warning me-2"></i>确认删除
                    </h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                </div>
                <div class="modal-body">
                    <p>确定要删除学生 "<span id="studentNameToDelete"></span>" 吗？</p>
                    <p class="text-muted small mb-0">
                        <i class="bi bi-info-circle me-1"></i>此操作不可恢复
                    </p>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                    <button type="button" class="btn btn-danger" id="confirmDeleteBtn">
                        <i class="bi bi-trash me-1"></i>确认删除
                    </button>
                </div>
            </div>
        </div>
    </div>

    <!-- Loading遮罩层 -->
    <div id="loadingOverlay" class="loading-overlay" style="display: none;">
        <div class="spinner-border text-primary" role="status">
            <span class="visually-hidden">加载中...</span>
        </div>
    </div>

    <!-- Toast容器 -->
    <div id="toastContainer" class="toast-container position-fixed bottom-0 end-0 p-3"></div>

    <div layout:fragment="content">
        <!-- Page Header -->
        <div class="d-flex justify-content-between align-items-center mb-4">
            <h2 class="h4 mb-0">
                <i class="bi bi-people-fill me-2"></i>学生管理
            </h2>
            <a th:href="@{/students/new}" class="btn btn-primary">
                <i class="bi bi-plus-lg me-1"></i>添加学生
            </a>
        </div>

        <!-- Search Card -->
        <div class="card search-card mb-4">
            <div class="card-body">
                <form class="search-form" method="get" th:action="@{/students}">
                    <div class="row g-3">
                        <div class="col-md-4">
                            <div class="input-group">
                                <span class="input-group-text bg-transparent border-end-0">
                                    <i class="bi bi-search"></i>
                                </span>
                                <input type="text" class="form-control border-start-0" 
                                       name="name" placeholder="按姓名搜索..."
                                       th:value="${param.name}">
                            </div>
                        </div>
                        <div class="col-md-4">
                            <div class="input-group">
                                <span class="input-group-text bg-transparent border-end-0">
                                    <i class="bi bi-bookmark"></i>
                                </span>
                                <input type="text" class="form-control border-start-0" 
                                       name="className" placeholder="按班级搜索..."
                                       th:value="${param.className}">
                            </div>
                        </div>
                        <div class="col-md-4">
                            <div class="d-grid d-md-flex justify-content-md-end">
                                <button type="submit" class="btn btn-primary me-md-2">
                                    <i class="bi bi-search me-1"></i>搜索
                                </button>
                                <a th:href="@{/students}" class="btn btn-secondary">
                                    <i class="bi bi-arrow-counterclockwise me-1"></i>重置
                                </a>
                            </div>
                        </div>
                    </div>
                </form>
            </div>
        </div>

        <!-- Alert Messages -->
        <div th:if="${message}" class="alert alert-success alert-dismissible fade show" role="alert">
            <i class="bi bi-check-circle-fill me-2"></i>
            <span th:text="${message}"></span>
            <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
        </div>

        <!-- Student Table -->
        <div class="card">
            <div class="card-body p-0">
                <div class="table-responsive">
                    <table class="table table-hover table-striped mb-0">
                        <thead>
                            <tr>
                                <th>学号</th>
                                <th>姓名</th>
                                <th>性别</th>
                                <th>年龄</th>
                                <th>班级</th>
                                <th>入学日期</th>
                                <th class="text-end">操作</th>
                            </tr>
                        </thead>
                        <tbody>
                            <tr th:if="${#lists.isEmpty(students)}">
                                <td colspan="7" class="text-center py-4">
                                    <div class="text-muted">
                                        <i class="bi bi-inbox-fill fs-4 d-block mb-2"></i>
                                        暂无学生数据
                                    </div>
                                </td>
                            </tr>
                            <tr th:each="student : ${students}">
                                <td>
                                    <span class="badge bg-light text-dark" th:text="${student.studentNumber}"></span>
                                </td>
                                <td th:text="${student.name}"></td>
                                <td>
                                    <span th:class="${student.gender == '男' ? 'text-primary' : 'text-danger'}"
                                          th:text="${student.gender}"></span>
                                </td>
                                <td th:text="${student.age}"></td>
                                <td>
                                    <span class="badge bg-info text-dark" th:text="${student.className}"></span>
                                </td>
                                <td th:text="${#temporals.format(student.enrollmentDate, 'yyyy-MM-dd')}"></td>
                                <td>
                                    <div class="action-buttons text-end">
                                        <a th:href="@{/students/edit/{id}(id=${student.id})}" 
                                           class="btn btn-sm btn-outline-primary me-1">
                                            <i class="bi bi-pencil"></i>
                                            <span class="d-none d-md-inline ms-1">编辑</span>
                                        </a>
                                        <button type="button" class="btn btn-sm btn-outline-danger"
                                                th:onclick="deleteStudent([[${student.id}]], [[${student.name}]])">
                                            <i class="bi bi-trash"></i>
                                            <span class="d-none d-md-inline ms-1">删除</span>
                                        </button>
                                    </div>
                                </td>
                            </tr>
                        </tbody>
                    </table>
                </div>
            </div>
        </div>
    </div>

    <!-- JavaScript -->
    <th:block layout:fragment="scripts">
        <script th:inline="javascript">
            let studentIdToDelete = null;
            let deleteModal = null;
            
            // 在DOM加载完成后初始化
            document.addEventListener('DOMContentLoaded', function() {
                // 初始化删除确认Modal
                deleteModal = new bootstrap.Modal(document.getElementById('deleteConfirmModal'));
                
                // 绑定确认删除按钮的点击事件
                document.getElementById('confirmDeleteBtn').addEventListener('click', handleDelete);
            });
            
            function deleteStudent(id, name) {
                studentIdToDelete = id;
                document.getElementById('studentNameToDelete').textContent = name;
                deleteModal.show();
            }
            
            function handleDelete() {
                if (!studentIdToDelete) return;
                
                showLoading();
                fetch(`/api/students/${studentIdToDelete}`, {
                    method: 'DELETE',
                    headers: {
                        'Content-Type': 'application/json'
                    }
                })
                .then(async response => {
                    if (!response.ok) {
                        let errorMessage = '删除失败';
                        try {
                            const errorData = await response.json();
                            errorMessage = errorData.message || errorData.error || errorMessage;
                        } catch (e) {
                            // 如果响应不是JSON格式，使用默认错误信息
                        }
                        throw new Error(errorMessage);
                    }
                    deleteModal.hide();
                    showToast('删除成功', 'success');
                    setTimeout(() => window.location.reload(), 500);
                })
                .catch(error => {
                    hideLoading();
                    deleteModal.hide();
                    let errorMessage;
                    if (error instanceof TypeError && error.message === 'Failed to fetch') {
                        errorMessage = '网络错误，请检查网络连接';
                    } else if (error.message.includes('404')) {
                        errorMessage = '该学生记录不存在或已被删除';
                    } else if (error.message.includes('403')) {
                        errorMessage = '您没有权限执行此操作';
                    } else if (error.message.includes('500')) {
                        errorMessage = '服务器内部错误，请稍后重试';
                    } else {
                        errorMessage = error.message || '删除失败，请重试';
                    }
                    showToast(errorMessage, 'danger');
                })
                .finally(() => {
                    studentIdToDelete = null;
                });
            }

            // 获取Loading遮罩层
            const loadingOverlay = document.getElementById('loadingOverlay');

            function showLoading() {
                loadingOverlay.style.display = 'flex';
            }

            function hideLoading() {
                loadingOverlay.style.display = 'none';
            }

            // Toast提示
            function showToast(message, type = 'success') {
                const toastContainer = document.getElementById('toastContainer');
                
                const toastElement = document.createElement('div');
                toastElement.className = `toast align-items-center text-white bg-${type} border-0`;
                toastElement.setAttribute('role', 'alert');
                toastElement.setAttribute('aria-live', 'assertive');
                toastElement.setAttribute('aria-atomic', 'true');
                
                toastElement.innerHTML = `
                    <div class="d-flex">
                        <div class="toast-body">
                            ${message}
                        </div>
                        <button type="button" class="btn-close btn-close-white me-2 m-auto" data-bs-dismiss="toast"></button>
                    </div>
                `;
                
                toastContainer.appendChild(toastElement);
                const toast = new bootstrap.Toast(toastElement);
                toast.show();
                
                toastElement.addEventListener('hidden.bs.toast', () => {
                    toastElement.remove();
                });
            }

            // 自动隐藏成功消息
            const alertElement = document.querySelector('.alert');
            if (alertElement) {
                setTimeout(() => {
                    const alert = bootstrap.Alert.getInstance(alertElement);
                    if (alert) {
                        alert.close();
                    }
                }, 3000);
            }
        </script>
    </th:block>
</body>
</html>